package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.common.pojos.ApComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    private MongoTemplate mongoTemplate;

    //查找热点评论
    @Override
    @Async("taskExecutor")  //异步执行此方法
    public void hotCommentExecutor(ApComment apComment) {
        //根据文章id查找文章中的热点评论,按照点赞数降序排列
        Query apCommentQuery = Query.query(Criteria.where("flag").is((short) 1).and("articleId").is(apComment.getArticleId()));
        Sort sort = Sort.by(Sort.Direction.DESC, "likes");
        apCommentQuery.with(sort);
        List<ApComment> apCommentList = mongoTemplate.find(apCommentQuery, ApComment.class);
        //非空判断
        if (apCommentList.size() == 0 || apCommentList.size() < 5) {
            //当前没有热点评论,直接将当前评论改成热点评论
            Update update = new Update();
            update.set("flag", (short) 1);
            Query query = Query.query(Criteria.where("_id").is(apComment.getId()));
            //修改到数据库
            mongoTemplate.updateFirst(query, update, ApComment.class);
        } else {
            //当前热点评论已经有5个,判断传入的评论点赞数是否超过点赞数最少的热点评论
            //获取apCommentList集合索引0的点赞数量
            int minLikesCount = apCommentList.get(0).getLikes();
            //记录点赞数量最少的评论的索引下标
            int index = 0;
            for (int i = 1; i < apCommentList.size(); i++) {
                ApComment comment = apCommentList.get(i);
                if (comment.getLikes() < minLikesCount) {
                    minLikesCount = comment.getLikes();
                    index = i;
                }
            }
            //判断传入的评论的点赞数是否大于热点评论中点赞数最少的
            if (apComment.getLikes() > minLikesCount) {
                //大于,将当前评论替换为热点文章
                Update update = new Update();
                update.set("flag", (short) 1);
                Query query = Query.query(Criteria.where("_id").is(apComment.getId()));
                //修改到数据库
                mongoTemplate.updateFirst(query, update, ApComment.class);
                //将被替换的评论修改为普通评论
                Update update2 = new Update();
                update2.set("flag", (short) 0);
                Query query2 = Query.query(Criteria.where("_id").is(apCommentList.get(index).getId()));
                //修改到数据库
                mongoTemplate.updateFirst(query2, update2, ApComment.class);
            }
        }
    }
}